﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using LFSRecord2.Model.Sound;

namespace LFSRecord2.Model.Media
{
    public class MediaAudio : MediaBase
    {
        public WaveStream AudioStream { get; private set; }

        public MediaAudio(string filePath)
        {
            MediaType = MediaTypes.Audio;
            IconType = MediaIconTypes.Audio;
            
            FilePath = filePath;
            FileStatus = MediaFileStatus.None;
            
            // Import file?
            if (FilePath.Length > 0)
            {
                loadFile();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                AudioStream.Dispose();
            }
        }

        public override void ReloadFile()
        {
            if (AudioStream != null)
                AudioStream.Dispose();
            resetFileInfo();

            // Import file?
            if (FilePath.Length > 0)
            {
                loadFile();
            }
        }

        protected override void ImportFile()
        {
            AudioStream = null;

            // Check if file exists
            if (!File.Exists(FilePath))
            {
                throw new FileNotFoundException();
            }

            // Detect type of audio file
            try
            {
                AudioStream = new WavStream(FilePath);
                populateFileInfo();
                return;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Wav import failed : " + ex.Message);
            }

            try
            {
                AudioStream = new AifStream(FilePath);
                populateFileInfo();
                return;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Aif import failed : " + ex.Message);
            }

            try
            {
                AudioStream = new Mp3Stream(FilePath);
                populateFileInfo();
                return;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Mp3 import failed : " + ex.Message);
            }

            throw new MediaImportException("Unknown format");
        }
    }
}
